<template>
	<div class="vue-box">
		<div class="c-panel">
			<!-- 主视图 -->
			<el-row v-if="!state.listShow">
				<!--左：组织树-->
				<el-col :span="4" :xs="24">
					<el-input
						placeholder="请输入部门名称" clearable size="small" v-model="treeFilterText" 
						prefix-icon="el-icon-search" style="margin-bottom: 20px"/>
						<el-tree style="display:'inline-block'" ref="tree" :filter-node-method="filterNode" default-expand-all highlight-current 
						:data="orgTree" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
				</el-col>
				<!--右：用户列表-->
				<el-col :span="20" :xs="24">
					<!--模糊查询-->
					<el-form :inline="true" size="small">
						<el-form-item label="用户昵称：">
							<el-input type="text" size="small" v-model="query.username" placeholder="模糊查询"></el-input>
						</el-form-item>
						<el-form-item label="状态：">
							<el-select size="small" v-model="query.status" placeholder="请选择" clearable>
								<el-option label="启用" value="1"></el-option>
								<el-option label="停用" value="0"></el-option>
							</el-select>
						</el-form-item>
						<br/>
						<el-form-item label="注册日期：">
							<el-date-picker type="date" size="small" v-model="query.startTime" value-format="yyyy-MM-dd" placeholder="开始日期"></el-date-picker> -
							<el-date-picker type="date" size="small" v-model="query.endTime" value-format="yyyy-MM-dd" placeholder="结束日期"></el-date-picker>
						</el-form-item>
						<el-form-item style="min-width: 0px;">
							<el-button type="primary" icon="el-icon-search" @click="f5()">查询</el-button>
						</el-form-item>
						<el-form-item style="min-width: 0px;">
							<el-button type="info" icon="el-icon-refresh" @click="f5('restart')">重置</el-button>
						</el-form-item>
						<br />
						<div class="buttonMargin">
							<el-form-item style="min-width: 0px;">
							<el-button type="success" plain icon="el-icon-plus" @click="add()">新增</el-button>
							</el-form-item>
							<el-form-item style="min-width: 0px;">
								<el-button type="danger" plain icon="el-icon-delete" @click="state.batchDelDialogVisible=true">删除</el-button>
							</el-form-item>
							<el-form-item style="min-width: 0px;">
								<el-button type="warning" plain icon="el-icon-download" @click="exportExcel()">导出</el-button>
							</el-form-item>
							<el-form-item style="min-width: 0px;">
								<el-button type="primary" icon="el-icon-refresh-left" @click="toggleSelection()">取消选择</el-button>
							</el-form-item>
						</div>
					</el-form>
					<!--数据列表-->
					<el-table :data="dataList" ref="multipleTable"  v-loading="state.loading" size="medium" @selection-change="handleSelectionChange">
						<el-table-column type="selection" width="40"></el-table-column>
						<el-table-column label="编号" type="index" align="center"></el-table-column>
						<el-table-column label="昵称" prop="username" width="260">
							<template slot-scope="s">
								<img :src="s.row.avatar" @click="sa.showImage(s.row.avatar, '400px', '400px')"
									style="width: 3.5em; height: 3.5em; float: left; margin-right: 1em; border-radius: 15%; cursor: pointer;" >
								<div style="float: left; width: 150px;margin-top:4px; line-height:20px;">
									<b>{{s.row.username}}</b>
									<p>{{s.row.email}}</p>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="性别" prop="sex" width="70" align="center"> </el-table-column>
						<!-- <el-table-column label="注册方式" prop="create_type"></el-table-column> -->
						<el-table-column label="注册时间"  prop="createTime" width="150" align="center"></el-table-column>
						<el-table-column label="状态" width="120" align="center">
							<template slot-scope="s">
								<el-switch @click.native="handleStatus(s.row)" active-color="#13ce66"
								v-model="s.row.status" active-value="1" inactive-value="0" inactive-color="#ff4949"></el-switch>
								<b style="color: green; margin-left: 10px;" v-if="s.row.status === 1||s.row.status === '1'">启用</b>
								<b style="color: red; margin-left: 10px;" v-else>停用</b>
							</template>
						</el-table-column>
						<el-table-column label="操作" align="center">
							<template slot-scope="s">
								<el-button type="primary" size="mini"  @click="get(s.row)">
									<i class="el-icon-view el-icon--left"></i>详情</el-button>
								<el-button type="warning" size="mini" @click="edit(s.row)">
									<i class="el-icon-edit el-icon--left"></i>修改</el-button>
								<el-button type="danger" size="mini" @click="state.delDialogVisible=true,info=s.row">
									<i class="el-icon-delete el-icon--left"></i>删除</el-button>	
							</template>
						</el-table-column>
					</el-table>
					<!--对话框相关-->
					<el-dialog title="用户管理" :visible.sync="state.dialogVisible" :modal-append-to-body='false'
					top='4vh' v-if="state.dialogVisible">
						<userInfo :info="JSON.stringify(info)" :displayType="state.displayType" :orgTree="orgTree"></userInfo>
					</el-dialog>
					<el-dialog title="修改提示" :visible.sync="state.stateDialogVisible"
							   :modal-append-to-body='false' width="30%" :before-close="handleClose">
						<span>确定要修改该用户状态吗</span>
						<span slot="footer" class="dialog-footer">
							<el-button type="primary" @click="updateStatus()">确 定</el-button>
							<el-button @click="noUpdateStatus()">取 消</el-button>
						</span>
					</el-dialog>
					<el-dialog title="删除提示" :visible.sync="state.delDialogVisible" :modal-append-to-body='false'
							   width="30%" :before-close="handleClose">
						<span>确定删除该用户？</span>
						<span slot="footer" class="dialog-footer">
							<el-button type="primary" @click="del()">确 定</el-button>
							<el-button @click="state.delDialogVisible=false">取 消</el-button>
						</span>
					</el-dialog>
					<el-dialog title="批量删除提示" :visible.sync="state.batchDelDialogVisible" :modal-append-to-body='false'
							   width="30%" :before-close="handleClose">
						<span>确定删除这些用户？</span>
						<span slot="footer" class="dialog-footer">
							<el-button type="primary" @click="batchDel()">确 定</el-button>
							<el-button @click="state.batchDelDialogVisible=false">取 消</el-button>
						</span>
					</el-dialog>
					<!-- 分页 -->
					<div class="page-box">
						<el-pagination background
							layout="total, prev, pager, next, sizes, jumper" 
							:current-page.sync="query.pageNo"
							:page-size.sync="query.pageSize"
							:total="dataCount" 
							:page-sizes="[1, 5, 10, 20, 30, 100]" 
							@current-change="f5()"
							@size-change="f5()">
						</el-pagination>
					</div>
				</el-col>
			</el-row>
		</div>
		<!-- 给自己打一波广告0.0 -->
		<div class="c-panel" style="background-color: rgba(0,0,0,0);">
			MyBlog：<el-link type="primary" href="http://muxyun.com/" target="_blank">
				站长的个人笔记 ———— 沐云博客
			</el-link>
		</div>
	</div>
</template>

<script>
//import { forEach } from '../case/mock-joptions';
//import mockData from './data-list.js';
import userInfo from './user-info.vue' 
	export default {
		data() {
			return {
				/*数据相关*/
        query: {	// 查询参数
          orgid:'',
					username: '',
					status:'',
					startTime: '',
					endTime: '',
					pageNo: 1,
					pageSize: 5,
				},
				defaultProps: {//组织树参数配置
					children: 'children',
					label: 'label'
				},
				dataCount: 0,
				treeFilterText:'',//组织树的筛选条件
				orgTree:[],
				dataList: [],//总数据列表
				multipleSelection: [],//当前选中行数组
				info:{},//目前操作的具体用户
				orginfo:null,//目前选择的部门
				/*标签状态相关*/
				state:{
					dialogVisible: false,//详情/修改/新增对话框的展示
					stateDialogVisible: false,//状态修改确认对话框
					delDialogVisible: false,//删除确认对话框
					batchDelDialogVisible: false,//删除确认对话框
					loading : false,//loading状态的判断
					displayType:''//控制展示是详情页还是修改页
				}
			}
		},
		watch:{
			info(newValue,oldValue){
				//console.log("info被修改,旧值为：");
				//console.log(oldValue);
				//console.log("info被修改,新值为：");
				//console.log(newValue);
			},
			//监听组织树模糊查询的输入框，发生变化就调用在el-tree标签上绑定的filter-node-method属性对应方法
			treeFilterText(val){
				this.$refs.tree.filter(val)
			}
		},
		components:{
			userInfo
		},
		methods: {
			// 数据刷新
			f5: function(type) {
				/* this.sa.ajax2('/user/getList', this.p, function(res){
					this.dataList = res.data;	// 数据  
					this.dataCount = res.dataCount;		// 分页  
				}.bind(this), {res: mockData}); */
				//上面的 {res: mockData}参数，就是把mockData赋值给res，模仿ajax请求收到回调参数
				this.state.loading=true;
        if(this.query.orgid===''){//id为1默认查询总组织下的所有用户
          this.query.orgid=1
        }
				if(this.orginfo!==undefined&&this.orginfo!==null){//如果当前选中了组织，那就查选中组织下的用户
					this.query.orgid=this.orginfo.id
				}
        let params=type==='restart'?{pageNo: 1,pageSize: 5,orgid: this.query.orgid}:this.query;
        console.log(params)
				//请求后台
        this.request('/api/user/list',params).then(res=>{
          if(!res){return}
          console.log(res)
          this.dataList=res.data;
          this.dataCount=res.dataCount;
          if(type!=="screen"){
            this.query= {orgid:this.query.orgid,username:'',status:'',start_time: '',end_time:'',
              pageNo:this.query.pageNo,pageSize:this.query.pageSize,dataCount:res.dataCount}
          }
          this.state.loading=false;
        })
			},
      //点击组织树上叶子时的回调
      handleNodeClick(data) {
        //console.log("获取组织叶下的用户");
        this.orginfo=data
        this.f5()
      },
			// 删除
			del: function() {
				this.sa.loading("删除中...");
				let params=this.info;
        this.request('/api/user/del',params).then(res=>{
          if(!res){return}
          this.sa.arrayDelete(this.dataList, this.info);
          this.dataCount=this.dataCount-1
          this.$message.success('删除成功');
          this.state.delDialogVisible=false
        })
        this.sa.hideloading();
			},
			// 查看
			get: function(data,type) {
				//console.log(arr);
        this.request('/api/user/get?id='+data.id).then(res=>{
          if(!res){return}
          data.pathname=res.data.org.pathname;
          data.orgName=res.data.org.orgName;
          data.leaderName=res.data.org.leaderName;
          if(res.data.role==null||res.data.role==undefined){
            data.roleName="暂未配置"
          }else{
            data.roleName=res.data.role.roleName;
          }
          this.info=data
          if(type=='edit'){
            //修改对话框标志为false，即展示修改页
            this.state.displayType='edit'
          }else{
            if(!this.zm.checkAuth('user:get')){
              this.$message.error("您暂无<查看用户详细信息>权限")
              return
            }
            this.state.displayType='info'
          }
          //所有数据准备完毕，显示对话框
          this.state.dialogVisible = true;
        })
			},
			//修改(调用修改对话框)
			edit: function(data) {
        if(!this.zm.checkAuth('user:update')){
          this.$message.error("您暂无<修改用户>权限")
          return
        }
        this.get(data,"edit")
			},
			//新增
			add(){
				//console.log("进来了..");
        if(!this.zm.checkAuth('user:add')){
          this.$message.error("您暂无<新增用户>权限！")
          return
        }
        this.state.displayType='add',
        this.state.dialogVisible=true;
			},
			//子组件新增用户成功后的回调
			addUser(){
				this.state.dialogVisible=false;
				this.f5();
			},
      //修改状态
      handleStatus(data){
        console.log("go")
        this.state.stateDialogVisible = true
        this.info=data
      },
			//取消修改状态(不调用修改对话框)
			noUpdateStatus(){
				//console.log(this.info);
				this.info.status=this.info.status==="1"?"0":"1";
				this.state.stateDialogVisible=false;
				this.$message.success("取消成功");
			},
			//确认修改状态(不调用修改对话框)
			updateStatus(){
        //这一步输出，status就已经被改了
        console.log(this.info)
				let arr=this.sa.keyListGet('permissionList');//数组形式
				if(!arr.includes('user:update')){
					this.$message.error("您暂无<修改用户>权限！")
					return
				}
				this.sa.loading("正在修改...")
				let params=this.info;
        this.request('/api/user/update',params).then(res=>{
          if(!res){return}
          console.log(this.dataList);
          this.$message.success("修改成功");
        })
        this.sa.hideloading();
				this.state.stateDialogVisible=false;
			},
			//修改用户信息的回调,用来保证组件共享数据的一致
			updateUserInfo(item){
				this.state.loading=true;
				this.f5()
				//这个纯有毒，不能做到即时，还是f5顺手
				/*this.sa.arrayUpdateById(this.dataList,item)*/
				this.state.dialogVisible=false;
				this.state.loading=false;	
				//console.log(this.dataList);
			},
			//批量删除
			batchDel(){
				let arr=this.sa.keyListGet('permissionList');//数组形式
				if(!arr.includes('user:del')){
					this.$message.error("您暂无<删除用户>权限！")
					return
				}
				let params=this.multipleSelection;
				if(params.length===0){
					this.$message.error("您尚未选择要操作的用户");
					return;
				}
        this.requestJson('/api/user/batchDel',params,{'Content-Type': 'application/json'}).then(res=>{
          if(!res){return}
          this.$message.success("删除成功！");
          this.state.batchDelDialogVisible=false;
          this.f5();
        })
			},
			//组织树筛选
			filterNode(value, data) {
				//value为搜索框的值，data为组织树数据
				if (!value) return true;
				return data.label.indexOf(value) !== -1;
			},
      //列表行选择
      handleSelectionChange(val){
        this.multipleSelection=val;
      },
      //对话框取消
      handleClose(done) {
        this.$confirm('确认关闭？')
            .then(_ => {
              done();
            })
            .catch(_ => {});
      },
      //取消当前的选择
      toggleSelection(){
        this.$refs.multipleTable.clearSelection();
      },
			//导出excel
			exportExcel(){
				if(!this.zm.checkAuth('user:export')){
					this.$message.error("您暂无<导出用户信息>权限")
					return
				}
        this.request('/api/user/export').then(res=>{
          if(!res){return}
          const file = new Blob([res], { type: "application/vnd.ms-excel" });
          const url = URL.createObjectURL(file);
          const a = document.createElement("a");
          a.href = url;
          a.click();
          this.isClick = true;
          this.$message.success("导出成功")
        })
			}
		},
		mounted(){
			//用户列表的数据请求
			this.f5();
			//获取组织树
      this.request('/api/org/getOrgTree').then(res=>{
        if(!res){return}
        this.orgTree=res.data;
      })
			//修改用户信息（单条）
			this.$bus.$on('updateUserInfo',this.updateUserInfo)
			//新增用户成功后取消弹框并刷新数据列表
			this.$bus.$on('addUser',this.addUser)
			//取消修改的回调绑定
			this.$bus.$on("noUpdate",()=>{
				this.state.dialogVisible=false
			})
		},
		beforeDestroy(){
			this.$bus.$off(['updateUserInfo','addUser','noUpdate'])
		}
	}
</script>


<style scoped>
/**模糊查询字体样式 */
/deep/.c-panel .el-form-item__label, .c-panel .c-label {
	font-size:14px;
	font-weight:900
}

/**组织树样式 */
/*最外层背景色。 字体颜色*/
/deep/.el-tree {
	background: none;
	color: #82b0ec;
	
}
/deep/.el-tree-node__label {
width: auto;
float: right;
font-size: 14px;
color: #1e1f1f;
line-height: 25px;
letter-spacing: 1px;
}

/* 鼠标失去焦点时节点背景的颜色 */
/deep/.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content{
  background: #b8e7e98a; 
}

/**下拉角标透明色*/
/deep/.el-tree-node__content:hover .el-tree-node__expand-icon.is-leaf {
	color: transparent;
}

/*当鼠标移动时,节点显示的背景色*/
/deep/.el-tree-node__content:hover {
	background-color:  #96c7c98a;
}



/*控制组织树与table平齐 */
/deep/.el-col-4{
	padding-top: 10px;
}
/*搜索表单，按钮和数据列表竖直方向不平齐 */
/*模糊搜索表单右移5px*/
/deep/.c-panel .el-form{
	margin-left:-5px
}
/*数据列表左移10px*/
/deep/.el-table{
	margin-left: 10px;
}
/*模糊搜索表单左移15px 缩短和列表的距离*/
.buttonMargin{
	margin-left: 15px;
	margin-bottom: -12px;
}
/*分页左移10px */
.page-box{
	margin-left: 10px;
}
</style>

